package com.jayqqaa12.service.system;

import com.jayqqaa12.common.Consts;
import com.jayqqaa12.jbase.jfinal.auto.BaseService;
import com.jayqqaa12.jbase.jfinal.ext.util.ListUtil;
import com.jayqqaa12.jbase.sdk.util.ShiroExt;
import com.jayqqaa12.model.system.Role;
import com.jayqqaa12.model.system.User;
import com.jayqqaa12.model.system.UserRole;
import com.jayqqaa12.shiro.ShiroCache;
import com.jfinal.plugin.activerecord.Db;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;

import java.util.Iterator;
import java.util.List;

/**
 * Generated by Jbase.
 */
public class UserService extends BaseService<User> {

	public static UserService me(){
		
		return me(UserService.class);
	}
	
	
    public User getUser(String id) {
        User u = dao.findById(id);
        List<Role> role = Role.dao.getRole(u.getId());

        u.put("role_ids", ListUtil.listToString(role, Role.ID));
        u.remove(User.CREATEDATE, User.PWD);
        return u;

    }

    public boolean changeStaus(Integer id, Integer status) {
        return dao.changeStaus(id,status);
    }

    /**
     * 其他用户 隐藏 admin
     */
    public List<User> list(int p, int c) {
        List<User> list = findAll(p, c).getList();
        Iterator<User> users = list.iterator();
        User now = ShiroExt.getSessionAttr(Consts.SESSION_USER);

        while (users.hasNext()) {
            User u = users.next();
            List<Role> role = Role.dao.getRole(u.getId());
            u.put("role_ids", ListUtil.listToString(role, Role.ID));
            u.put("role_names", ListUtil.listToString(role, Role.NAME));
            if (u.getId() == 1 && now.getId() != 1) users.remove();
        }

        return list;
    }
    public boolean grant(Integer[] role_ids, User u) {

        if (u.getId() != null) u.encrypt().update();
        else SecurityUtils.getSubject().getSession().setAttribute(Consts.SESSION_EAMIL_USER, u);

        boolean result = UserRole.dao.deleteByWhere("where user_id=?", u.getId());

        if (role_ids == null) return result;

        Object[][] params = ListUtil.ArrayToArray(u.getId(), role_ids);
        result = Db.batch("insert into system_user_role(user_id,role_id)  values(?,?)", params, role_ids.length).length > 0;

        ShiroCache.clearAuthorizationInfoAll();

        return result;
    }

	public void login(String[] result) {
		
		UsernamePasswordToken token = new UsernamePasswordToken(result[0], result[1]);
		Subject subject = SecurityUtils.getSubject();
		if (!subject.isAuthenticated()) {
			token.setRememberMe(false);
			subject.login(token);
			User u = User.dao.findByEmail(result[0]);
			subject.getSession(true).setAttribute(Consts.SESSION_USER, u);
		}
		
	}

	public SimpleAuthenticationInfo getAuthInfo(String username,String name) {
		
		
		User user = User.dao.findByEmail(username);

		if (user == null) throw new UnknownAccountException();// 没找到帐号
		if (user.getStatus().equals(2)) throw new LockedAccountException(" USER Freeze");

		
		return new SimpleAuthenticationInfo(user.getEmail(), user.getPwd(), ByteSource.Util.bytes(user
				.getSalt()), name);
		
	}

	public AuthorizationInfo getAuthUrl(String loginName) {
		User user = User.dao.findByEmail(loginName);

		if (user != null) {
			SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
			info.addRoles(user.getRolesName(user.getName()));
			for (String role : info.getRoles()) {
				info.addStringPermissions(Role.dao.getResUrl(role));
			}

			return info;

		} else return null;
	}

	public boolean existEmail(String email) {
		return dao.findByEmail(email)!=null;
	}
	
	
}
